var util = require('../utils/zhUtil.js');
const API_BASE = 'https://news-at.zhihu.com/api';
const API_V4 = API_BASE + '/4';
const API_V3 = API_BASE + '/3';

const API_NEWS = API_V4 + '/news';
const API_STORY = API_V4 + '/story';

function getNewsLatest(successCallback, errorCallback, completeCallback) {
  requestData(API_NEWS + '/latest', {}, successCallback, errorCallback, completeCallback);
}
/**
 * 获取以往日报 
 * 知乎日报最早20130519
 * @param {string} date 日期 yyyMMdd
 * @returns {string}
 */
function getBeforeNews(date, successCallback, errorCallback, completeCallback) {
  requestData(API_V4 + '/news/before/' + date, {}, successCallback, errorCallback, completeCallback);
}

function getNewsDetail(newsId, successCallback, errorCallback, completeCallback) {
  requestData(API_NEWS + '/' + newsId, {}, successCallback, errorCallback, completeCallback);
}

function getStoryShortComments(storyId, successCallback, errorCallback, completeCallback) {
  requestData(API_STORY + '/' + storyId + '/short-comments', {}, successCallback, errorCallback, completeCallback);
}

function getStoryLongComments(storyId, successCallback, errorCallback, completeCallback) {
  requestData(API_STORY + '/' + storyId + '/long-comments', {}, successCallback, errorCallback, completeCallback);
}

/**
 * 获取新闻额外的评论数量和点赞数量等信息
 * @param {int} newsId 日报id
 * @returns {string}
 */
function getStoryExtraInfo(storyId, successCallback, errorCallback, completeCallback) {
  requestData(API_STORY + '-extra/' + storyId, {}, successCallback, errorCallback, completeCallback);
}

/**
 * 网络请求方法
 * @param url {string} 请求url
 * @param data {object} 参数
 * @param successCallback {function} 成功回调函数
 * @param errorCallback {function} 失败回调函数
 * @param completeCallback {function} 完成回调函数
 * @returns {void}
 */
function requestData(url, data, successCallback, errorCallback, completeCallback) {
  wx.request({
    url: url,
    data: data,
    header: { 'Content-Type': 'application/json' },
    success: function (res) {
      if (res.statusCode == 200)
        util.isFunction(successCallback) && successCallback(res.data);
      else
        util.isFunction(errorCallback) && errorCallback();
    },
    error: function () {
      util.isFunction(errorCallback) && errorCallback();
    },
    complete: function () {
      util.isFunction(completeCallback) && completeCallback();
    }
  });
}


module.exports = {
  getNewsLatest: getNewsLatest,
  getBeforeNews: getBeforeNews,
  getNewsDetail: getNewsDetail,
  getStoryExtraInfo: getStoryExtraInfo,
  getStoryLongComments: getStoryLongComments,
  getStoryShortComments: getStoryShortComments
};
